package cn.mafangui.hotel.controller.user;

import cn.mafangui.hotel.entity.*;
import cn.mafangui.hotel.enums.OrderStatus;
import cn.mafangui.hotel.mapper.RoomTypeMapper;
import cn.mafangui.hotel.mapper.UserVipLevelMapper;
import cn.mafangui.hotel.response.AjaxResult;
import cn.mafangui.hotel.response.MsgType;
import cn.mafangui.hotel.response.ResponseTool;
import cn.mafangui.hotel.service.OrderService;
import cn.mafangui.hotel.service.RoomService;
import cn.mafangui.hotel.service.UserService;
import cn.mafangui.hotel.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 订单接口
 */
@RestController
@RequestMapping(value = "/user/order")
@CrossOrigin("*")
public class UserOrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;

    @Resource
    private RoomService roomService;

    @Resource
    private RoomTypeMapper roomTypeMapper;
    @Resource
    private UserVipLevelMapper userVipLevelMapper;

    /**
     * 添加预订
     * 订单状态默认为未付款状态
     * @param orderTypeId
     * @param orderType
     * @param userId
     * @param name
     * @param phone
     * @param roomTypeId
     * @param roomType
     * @param orderDate
     * @param orderDays
     * @param orderCost
     * @return
     */
    @RequestMapping(value = "/add")
    @Transactional
    public AjaxResult addOrder(int orderTypeId,String orderType, int userId,String name, String phone,int roomTypeId, String roomType,
                        @DateTimeFormat(pattern = "yyyy-MM-dd") Date orderDate, Integer orderDays, Double orderCost,String roompassword){
        orderDate = new Date();
        Order order = new Order(0,orderTypeId,orderType,userId,name,phone,roomTypeId,
                roomType,orderDate,orderDays, OrderStatus.UNPAID.getCode(),orderCost,roompassword);

        List<Room> rooms = roomService.selectByType(roomTypeId);
        for (Room room : rooms) {
            if (room.getRoomStatus() == 1){
                order.setRoomNumber(room.getRoomNumber());
                room.setRoomStatus(0);
                roomService.update(room);
                break;
            }
        }
        if (order.getRoomNumber() == null){
            return ResponseTool.failed("房间不足");
        }

        // 费用
//        User user = userService.selectById(userId);
//        RoomType type = roomTypeMapper.selectByPrimaryKey(roomTypeId);
//        double discount = 1.0;
//        for (UserVipLevel userVipLevel : userVipLevelMapper.findAll()) {
//            if (userVipLevel.getViplevel().equals(String.valueOf(user.getViplevel()))){
//                discount = userVipLevel.getDiscount();
//                break;
//            }
//        }
//        order.setOrderCost(order.getOrderDays() * type.getPrice() * discount);

        order.setOrderTypeId(1);

        order.setCreateTime(new Date());
        int re = orderService.addOrder(order);
        if(re!=1) ResponseTool.failed(MsgType.FAILED);
        return ResponseTool.success(MsgType.SUCCESS);
    }


    /**
     * 删除订单
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/delete")
    public AjaxResult deleteOrderByUser(int orderId){
        Order order = new Order(orderId,OrderStatus.WAS_DELETED.getCode());
        int re =  orderService.update(order);
        if(re!=1) ResponseTool.failed(MsgType.FAILED);
        return ResponseTool.success(MsgType.SUCCESS);
    }


    /**
     * 订单支付
     * @param orderId
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/pay")
    public AjaxResult payOrder(Integer orderId, String username, String password, HttpServletRequest request){
        //User user = userService.selectByUsernameAndPassword(username,password);
        int userId = (int) request.getSession().getAttribute("userId");
        User user = userService.selectById(userId);
        if(user==null) return ResponseTool.failed("密码错误");
        if (user.getMoney() < orderService.selectById(orderId).getOrderCost()) return ResponseTool.failed("余额不足");
        if(!user.getPaypassword().equals(MD5Utils.MD5Encode(password))) return ResponseTool.failed("密码错误");
        int re = orderService.payOrder(orderId);
        if(re!=1) ResponseTool.failed(MsgType.FAILED);
        user.setMoney(user.getMoney() - orderService.selectById(orderId).getOrderCost());
        userService.updateUser(user);

        Room room = roomService.selectByNumber(orderService.selectById(orderId).getRoomNumber());
        room.setRoomStatus(0);
        roomService.update(room);
        return ResponseTool.success(MsgType.SUCCESS);
    }

    /**
     * 取消订单
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/cancel")
    public AjaxResult cancelOrder(int orderId){
        int re = orderService.cancelOrder(orderId);
        if(re!=1) ResponseTool.failed(MsgType.FAILED);
        return ResponseTool.success(MsgType.SUCCESS);
    }


    /**
     * 客户查询个人所有订单（不包括被自己删除的）
     * @param userId
     * @return
     */
    @RequestMapping(value = "")
    public AjaxResult getAllByUser(int userId){
        return ResponseTool.success(orderService.UsersAllOrders(userId));
    }

    /**
     * 根据订单号查询订单
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/{orderId}")
    public AjaxResult getById(@PathVariable int orderId){
        return ResponseTool.success(orderService.selectById(orderId));
    }

}
